<?php 

import('@.com.99ebc.lib.Error');
import('@.com.99ebc.lib.File');
import('@.com.99ebc.lib.Xml');

import("ORG.Util.Image");

class GjdzModel extends RelationModel {
    //表字段配置
    protected $fields   = array(
                                'gjdz_id',
                                'gjdz_name',
                                'gjdz_type',
                                'sort_loc',
                                'gjdz_typeinfo',
                                'jump_url',
                                'gjdz_res',
                                'gjdz_rule',
                                'gjdz_price',
                                'gjdz_desc',
                                'image_path',
                                'edit_time',
                                '_pk' => 'gjdz_id',
                                '_autoinc' => true
                            );
    
    //自动验证
    protected $_validate    = array(
        array('gjdz_name', 'require', '名称不能为空！'),
        array('sort_loc', 'number', '排序编号必须是数字！',2),
        array('jump_url', 'url', '跳转链接无效！',2)
    );

    //自动完成
    protected $_auto        = array(
        array('edit_time', 'mktime', 3, 'function')
    );

    //自动关联配置
    protected $_link    = array(
        'gjdz_type' => array(
            'mapping_type' => BELONGS_TO,
            'class_name' => 'Gjdztype',
            'foreign_key' => 'gjdz_type',
            'as_fields' => 'gjdztype_name'
        )
    );

    protected static $orderFields = 'sort_loc';

    protected static $xmlFields   = '`gjdz_name`, `image_path`, `gjdz_res`, `gjdz_rule`, `gjdz_price`, `gjdz_desc`, `jump_url`';

    protected $_imageTypes;
    protected $_imageSize;
    protected $_uploadDir;

    protected $_countWhere;
    protected $_modelTypeId;

    protected $_error;
    protected $_gjdztype;

    //默认详细信息里显示的图片类型
    protected static $infoImgType     = '_s';
    //格式:width, height, type, interlace, 后缀
    protected static $thumbImgInfo  = array(
        '_s' => array('w' => 65, 'h' => 50, 't' => 'jpg', 'i' => true)
    );

    //XML配置参数
    protected static $xmlFilePath   = 'xml/gjdz_type_%d.xml';

    protected static $rootNode      = '
<gjdz_show>
    %s
</gjdz_show>';

    protected static $childNode     = "
<member>
    <title><![CDATA[%s]]></title>
    <name><![CDATA[%s]]></name>
    <(ture>%s</(ture>
    <info><![CDATA[<font color=\"#FFFFFF\">产品详细介绍 </font>
%s
]]></info>
</member>";

    public function __construct() {
        parent::__construct();

        $this->_countWhere  = '';
        $this->_modelTypeId = 0;
        $this->_imageSize   = 2;
        $this->_gjdztype    = null;
        $this->_imageTypes  = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
        $this->_uploadDir   = 'Public/default/uploadfiles/gjdz';
        $this->_error       = new Error(); 
    }

    //得到记录总数
    public function getCountRecords() {
        return $this->where($this->_countWhere)->count();
    }
    
    //搜索方法
    public function searchGjdz($page = 0, $keyword, $perPage = 10) {
        if(preg_match('/^\/+\d+$/', $keyword)) {
            $whereSearch  = '`gjdz_id` = ' . strtr($keyword, array('/' => ''));
        } else {
            $whereSearch  = '`gjdz_name` like \'%' . $keyword . '%\'';
        }
        $this->_countWhere  = $whereSearch;

        return $this->seeGjdz($page, $whereSearch, $perPage);
    }

    //查看列表方法 
    public function seeGjdz($page = 0, $whereGjdz = '', $perPage = 10) {
        if(empty($whereGjdz)) {
            $whereGjdz       = $this->genWhereModelType();
            $this->_countWhere  = $whereGjdz;
        }
        return $this->relation(true)->where($whereGjdz)->order(self::$orderFields)->limit($perPage)->page($page)->select();
    }

    //查看记录详细信息方法
    public function infoGjdz($recordId) {
        $record     = $this->where('`gjdz_id` = ' . $recordId)->find();
        if(!empty($record['image_path'])) {
            $record['image_path_small']     = $this->genThumbImageName($record['image_path']) . self::$infoImgType . '.' . self::$thumbImgInfo[self::$infoImgType]['t']; 
        }
        $this->_modelTypeId     = $record['gjdz_type'];
        
        return $record;
    }

    //编辑记录方法
    public function editGjdz($recordId) {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        if(isset($_POST['del_image'])) {
            if(!empty($_POST['del_image'])) {
                if(false === $this->deleteFile($_POST['old_image_path'])) {
                    Logger::log('删除文件失败！' . $_POST['old_image_path']);
                } else {
                    $_POST['image_path']= '';
                }
            } else {
                $_POST['image_path']    = $_POST['old_image_path'];
            }
        }
        $this->isUserGjdztypeInfo();
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->save()) {
            return $this->getError();
        }

        return true;
    }

    //添加记录方法
    public function addGjdz() {
        if(false === $this->uploadFile()) {
            return $this->_error->getErrorInfo();
        }
        $this->isUserGjdztypeInfo();
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->add()) {
            return false;
            return $this->getError();
        }

        return true;
    }

    //检测是否使用所属高级定制的产品信息
    protected function isUserGjdztypeInfo() {
        if(isset($_POST['gjdz_typeinfo']) && $_POST['gjdz_typeinfo'] > 1) {
            $this->_gjdztype    = $this->getGjdztypeObject();
            $gjdztypeInfo       = $this->_gjdztype->infoGjdztype($_POST['gjdz_type']);
            $_POST['jump_url']  = $gjdztypeInfo['jump_url'];
            $_POST['gjdz_res']  = $gjdztypeInfo['gjdztype_res'];
            $_POST['gjdz_rule'] = $gjdztypeInfo['gjdztype_rule'];
            $_POST['gjdz_price']= $gjdztypeInfo['gjdztype_price'];
            $_POST['gjdz_desc'] = $gjdztypeInfo['gjdztype_desc'];
        }
    }

    protected function getGjdztypeObject() {
        if($this->_gjdztype == null) {
            return D('Gjdztype');
        }

        return $this->_gjdztype;
    }

    //删除记录方法
    public function deleteGjdz($recordId) {
        return $this->quickDeleteGjdz(array($recordId));
    }

    //快捷操作：删除记录
    public function quickDeleteGjdz(array $recordIds){
        $this->quickDeleteImageGjdz($recordIds);
        $whereStr   = $this->genWhereIn('gjdz_id', $recordIds);

        return $this->where($whereStr)->delete();
    }

    //快捷操作：删除记录相关文件
    public function quickDeleteImageGjdz(array $recordIds) {
        $whereStr   = $this->genWhereIn('gjdz_id', $recordIds) . ' AND (`image_path` !=\'\' AND `image_path` IS NOT NULL)';
        $recordList = $this->where($whereStr)->field('gjdz_id, image_path')->select();
        if(empty($recordList)) {
            return ture;
        }
        $whereStr   = '`gjdz_id` IN (';
        foreach($recordList as $record) {
            if($this->deleteFile($record['image_path'])) {
                $whereStr   .= $record['gjdz_id'] . ', ';
            }
        }
        $whereStr    .= '-1)'; 

        return $this->where($whereStr)->setField('image_path', '');
    }

    //生成FLASH调用的XML文件
    public function xmlGjdz($gjdztypeId = 0) {
        if(!empty($gjdztypeId)) {
            $whereType          = "`gjdz_type` = " . $gjdztypeId;
            $this->_countWhere  = $whereType;
        } else {
            $whereType  = $this->genWhereModelType();
        }
        $perPage        = 10;
        $totalRows      = $this->getCountRecords();
        $totalPage      = ceil($totalRows / $perPage);
        for($page = 0; $page < $totalPage; $page ++) {
            $recordList     = $this->getXmlRecordList($whereType, $page, $perpage);
            $xmlContent     .= $this->genXmlContent($recordList);
        }
        if(false === $this->writeXml($xmlContent)) {
            Logger::log('写入XML内容失败！' . __CLASS__);
        }

        return true;
    }

    //根据主类的信息来同步符合条件的记录信息
    public function syncGjdzinfo($gjdztypeId = '', $transData) {
        if(empty($gjdztypeId)) {
            return false;
        }
        $updateData['jump_url']     = $transData['jump_url'];
        $updateData['gjdz_res']     = $transData['gjdztype_res'];
        $updateData['gjdz_rule']    = $transData['gjdztype_rule'];
        $updateData['gjdz_price']   = $transData['gjdztype_price'];
        $updateData['gjdz_desc']    = $transData['gjdztype_desc'];
        $whereStr   = '`gjdz_type` = ' . $gjdztypeId . ' AND `gjdz_typeinfo` = 2';

        return $this->where($whereStr)->data($updateData)->save();
    }
    
    //得到XML的数据集
    protected function getXmlRecordList($whereType = '', $page, $perpage = 10) {
        return $this->field(self::$xmlFields)->where($whereType)->order(self::$orderFields)->page($page, $perpage)->select();
    }

    //写入XML文件内容
    protected function writeXml($xmlContent) {
        $xmlContent     = sprintf(self::$rootNode, $xmlContent);
        $this->_xmlFilePath = sprintf(self::$xmlFilePath, $this->_modelTypeId);
        $xml                = new Xml($this->_xmlFilePath, $xmlContent);
        $this->_modelTypeId ++;
        
        return  $xml->save();

    }

    //生成主页的XML内容
    protected function genXmlContent($recordList) {
        if(empty($recordList)) {
            return '';
        }
        foreach($recordList as $record) {
            $xmlContent .= vsprintf(self::$childNode, $this->getXmlData($record));
        }

        return $xmlContent;
    }

    //得到需要的XML数据
    protected function getXmlData($record) {
        $xmlData['name_res']  = $record['gjdz_name'] . '<br/>' . $record['gjdz_res'];
        $xmlData['name']      = $record['gjdz_name'];
        if(!empty($record['image_path'])) {
            $xmlData['image_path']  = $this->_uploadDir . '/' . $record['image_path'];
        } else {
            $xmlData['image_path']  = '';
        }
        $xmlData['desc']      = '';
        if(!empty($record['gzdj_res'])) {
            $xmlData['desc']  .= '材质：' . $record['gjdz_res'] . '<br/>';
        }
        if(!empty($record['gjdz_rule'])) {
            $xmlData['desc']  .= '尺码：' . $record['gjdz_rule'] . '<br/>';
        }
        if(!empty($record['gjdz_price'])) {
            $xmlData['desc']  .= '价格：<font color="#fff000">' . $record['gjdz_price'] . '</font><br />';
        }
        $xmlData['desc']      .= $record['gjdz_desc'];
        if(!empty($record['jump_url'])) {
            $xmlData['desc']  .= '<br/><br/><a href=\"' . $record['jump_url'] . '\"><img src=\"gjdzs_show/images/shop_car.png\" width=\"231\" height=\"37\" algin=\"left\"/> </a><br />';
        }

        return $xmlData;
    }

    //生成WhereIn条件语句
    protected function genWhereIn($field, array $values) {
        return '`' . $field . '` IN (' . implode(',', $values) . ', -1)';
    }

    //生成模块类型的条件查询片段
    protected function genWhereModelType() {
        if(isset($_GET['type']) && !empty($_GET['type'])) {
            $this->_modelTypeId     = $_GET['type'];
            return '`gjdz_type` = ' . $_GET['type'];
        }
        
        return '';
    }

    //上传文件方法
    protected function uploadFile() {
        if(!empty($_FILES['image_path']['name'])) {
            $uploadFile     = new UploadFile($_FILES['image_path'],
                                        $this->_uploadDir,
                                        $this->_imageTypes,
                                        $this->_imageSize);
            if(false === $uploadFile->upload()) {
                $this->_error->setErrorInfo($uploadFile->getError());
                return false;
            }
            $arrPath    = explode('/', $uploadFile->getUploadFilePath());
            $_POST['image_path']    = array_pop($arrPath);
            $_POST['image_path']    = array_pop($arrPath) . '/' . $_POST['image_path'];
            //生成缩略图
            $this->genThumbImage($uploadFile->getUploadFilePath());
            
            return true;
        }

        return true;
    }

    //生成缩略图
    protected function genThumbImage($srcFilePath) {
        $thumbImgName  = $this->genThumbImageName($srcFilePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            $genResult      = Image::thumb($srcFilePath, $thumbImgPath, $thumbInfo['t'], $thumbInfo['w'], $thumbInfo['h'], $thumbInfo['i']);
            if(!$genResult) {
               //log 
            }
        } 
    }

    //得到缩略图的路径及文件名
    public function genThumbImageName($srcFilePath) {
        return mb_substr($srcFilePath , 0, strrpos($srcFilePath, '.'), 'utf-8');
    }

    //得到缩略图路径
    public function getThumbImagePath($srcFilePath) {
       return $this->_uploadDir . '/' . $this->genThumbImageName($srcFilePath) . '_s.' . self::$thumbImgInfo['_s']['t'];
    }

    //这个将会作为一个interface
    protected function deleteFile($filePath) {
        if(!empty($filePath)) {
            $this->delThumbImageFile($filePath);
            return LittleTools::deleteFile($filePath, $this->_uploadDir);
        }

        return true;
    }

    //删除相关缩略图
    protected function delThumbImageFile($filePath) {
        $thumbImgName  = $this->genThumbImageName($filePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            LittleTools::deleteFile($thumbImgPath, $this->_uploadDir);
        } 
    }

    public function getUploadDir() {
        return preg_replace('/public/i', '', $this->_uploadDir);
    }

    //得到模块的类型ID
    public function getModelTypeId() {
        if(empty($this->_modelTypeId)) {
            return $_GET['type'];
        }

        return $this->_modelTypeId;
    }


}

?>
